<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use PDO;
use Think\Exception;
use wxpay\wxpay;
use alipay\Alipay;
use epay\epay;
use app\admin\model\Goods as GoodsModel;
use app\admin\model\Order as OrderModel;
use app\admin\model\Travelers as TravelersModel;
use app\admin\model\reward\Log as RewardLogModel;
use app\admin\model\card\Log as CardLogModel;
use app\admin\model\agent\Log as AgentLogModel;
use think\Request;

class Order extends Api
{
    protected $noNeedRight = '*';
    protected $noNeedLogin = ['notifyx','payOrderNotify'];


    /**
     * 商城下单
     */
    public function createOrder()
    {
        if($this->auth->is_vip == 0)
        {
            $this->error("非会员，无法预约");
        }
        $goods_id = $this->request->post('goods_id', 0);
        if($goods_id == 0)
        {
            $this->error('请选择出行路线',[]);
        }
        $travelers_id = $this->request->post('travelers_id','');
        if(!$travelers_id)
        {
            $this->error('请选择出行人',[]);
        }
        $goods_where['id'] = $goods_id;
        $shop_info = GoodsModel::where($goods_where)->field("fx_pirce,zt_rate,jt_rate,id as goods_id,goods_name,pirce as price,good_images,v_pirce as v_price")->find();
        if(!$shop_info)
        {
            $this->error('出行路线不存在',[]);
        }
        
        $travelers_id_list = explode(',',$travelers_id);
        
        $ooid = 'C' . date('Ymd') . substr(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);

        $total_price = $shop_info['v_price'];
        $is_pay = 1;
        if($total_price > 0)
        {
            $is_pay = 0;
        }
        // 获取我的上级和上上级
        $card_log = CardLogModel::where('user_id', $this->auth->id)->find();
        $order = [
            'goods_id' => $goods_id,
            'out_trade_no' => $ooid,
            'user_id' => $this->auth->id,
            'price'=>$shop_info['price'],
            'a_price'=>$shop_info['v_price'],
            'goods_name' => $shop_info['goods_name'],
            'good_images' => $shop_info['good_images'],
            'fx_pirce' => 0,
            'fx_pirce2'=>$shop_info['fx_pirce'],
            'zt_rate' => $shop_info['zt_rate'],
            'jt_rate' => $shop_info['jt_rate'],
            'zt_user_id' => $card_log ? $card_log->agent_id : 0,
            'jt_user_id' => $card_log ? $card_log->tagent_id : 0,
            'travelers_id' => $travelers_id,
            'travelers_count' => count($travelers_id_list),
            'create_time' => time(),
            'is_pay'=>$is_pay
        ];
        $status = OrderModel::insertGetId($order);
        if($status)
        {
            if($is_pay == 0)
            {
                $return['to_pay'] = 1;
                $return['out_trade_no'] = $ooid;
                $return['v_price'] = $shop_info['v_price'];
                $this->success('下单成功',$return);
            }
            //获取上级
            $card_info = CardLogModel::where('user_id',$this->auth->id)->find();
            {
                $order_data = [];
                if($card_info && $shop_info['fx_pirce'])
                {
                    $order_data['zt_user_id'] = $card_info['agent_id'];
                    $log = [
                        'user_id'=>$this->auth->id,
                        'agent_id'=>$card_info['agent_id'],
                        'money'=>round($shop_info['fx_pirce']*$shop_info['zt_rate']/100,2),
                        'memo'=>'下级出行',
                        'order_id'=>$status,
                        'createtime'=>time(),
                    ];
                    RewardLogModel::insertGetId($log);
                    
                    $card_info2 = AgentLogModel::where('user_id',$card_info['agent_id'])->find();
                    if($card_info2 && $card_info2['agent_id'])
                    {
                        $order_data['jt_user_id'] = $card_info2['agent_id'];
                        $log = [
                            'user_id'=>$this->auth->id,
                            'agent_id'=>$card_info2['agent_id'],
                            'money'=>round($shop_info['fx_pirce']*$shop_info['jt_rate']/100,2),
                            'memo'=>'下级出行',
                            'createtime'=>time(),
                            'order_id'=>$status,
                            'level'=>2
                        ];
                        RewardLogModel::insertGetId($log);
                        
                    }
                }
                if($order_data)
                {
                    OrderModel::where('id',$status)->update($order_data);
                }
            }
            $return['to_pay'] = 0;
            $this->success('下单成功',$return);
        }
        $this->error('下单失败',[]);
    }
    
    public function payOrder()
    {
        $order_no = $this->request->post("order_no",'');
        if($order_no == '')
        {
            $this->error('支付订单信息错误，请重试',[]);
        }
        $order_where['out_trade_no'] = $order_no;
        $order_where['user_id'] = $this->auth->id;
        $order_info = OrderModel::where($order_where)->find();
        if(!$order_info)
        {
            $this->error('支付订单信息错误，请重试',[]);
        }
        if($order_info['is_pay'] == 1)
        {
            $this->error('您已支付');
        }
        $title = '旅游服务购买';
        $Wxpay = new \app\admin\library\Wxpay();
        $url = 'https://travel.fastwork.vip/';
        $res = $Wxpay->wxPay($order_no,$order_info['a_price'],$title,$url.'/api/order/payOrderNotify','jsapi',$this->auth->wx_mini_openid);
        if($res['code'] == 1)
        {
            $this->success("获取成功",$res['data']);
        }
        $this->error("支付失败",[]);
    }
    
     public function payOrderNotify()
    {
        
        $header = Request::instance()->header();
        $inWechatpaySignature = $header['wechatpay-signature'];
        $inWechatpayTimestamp = $header['wechatpay-timestamp'];
        $inWechatpaySerial = $header['wechatpay-serial'];
        $inWechatpayNonce = $header['wechatpay-nonce'];

        $Wxpay = new \app\admin\library\Wxpay();
        if (!$inWechatpaySignature or !$inWechatpayTimestamp or !$inWechatpaySerial or !$inWechatpayNonce) {
            header("Location:/404.html");
            exit;
        }
        $inBody = file_get_contents('php://input');
        $check_res = $Wxpay->checkSign($inWechatpaySignature,$inWechatpayTimestamp,$inWechatpayNonce,$inBody);
        //$check_res['out_trade_no'] = 'A2023062949975452';
        if($check_res)
        {
            Db::startTrans();
            try{
                $out_trade_no = $check_res['out_trade_no'];
                $order_info = OrderModel::where('out_trade_no',$out_trade_no)->find();
                if(!$order_info)
                {
                    $str = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>';
                    return $str;
                }
                if($order_info['is_pay'] == 1)
                {
                    $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                    return $str;
                }
                $str = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>';
                
                $order_data['is_pay'] = '1';
                $order_data['pay_time'] = time();
                $status = OrderModel::where('out_trade_no',$out_trade_no)->update($order_data);
                if($status === false)
                {
                    Db::rollback();
                    
                    echo $str;die;
                }
                
                
                
                //获取上级
                $card_info = CardLogModel::where('user_id',$order_info['user_id'])->find();
                {
                    $order_data = [];
                    if($card_info && $order_info['fx_pirce'])
                    {
                        $order_data['zt_user_id'] = $card_info['agent_id'];
                        $log = [
                            'user_id'=>$order_info['user_id'],
                            'agent_id'=>$card_info['agent_id'],
                            'money'=>round($order_info['fx_pirce']*$order_info['zt_rate']/100,2),
                            'memo'=>'下级出行',
                            'order_id'=>$status,
                            'createtime'=>time(),
                        ];
                        RewardLogModel::insertGetId($log);
                        
                        $card_info2 = AgentLogModel::where('user_id',$card_info['agent_id'])->find();
                        if($card_info2 && $card_info2['agent_id'])
                        {
                            $order_data['jt_user_id'] = $card_info2['agent_id'];
                            $log = [
                                'user_id'=>$order_info['user_id'],
                                'agent_id'=>$card_info2['agent_id'],
                                'money'=>round($order_info['fx_pirce']*$order_info['jt_rate']/100,2),
                                'memo'=>'下级出行',
                                'createtime'=>time(),
                                'order_id'=>$status,
                                'level'=>2
                            ];
                            RewardLogModel::insertGetId($log);
                            
                        }
                    }
                    if($order_data)
                    {
                        OrderModel::where('id',$status)->update($order_data);
                    }
                }
                
                Db::commit();
                $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                return $str; 
            }catch(Expection $e)
            {
                Db::rollback();
            }
            
            
            
            
            $str = '<xml><return_code><![CDATA[FAIL3]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>';
            return $str;
        }
    }
    
    public function getOrder()
    {
        $type = $this->request->post('status','');
        $where = [];
        if($type != '')
        {
            $where['status'] = $type;
        }
        $where['is_pay'] = 1;
        $where['user_id'] = $this->auth->id;
        $page = $this->request->post("page",1);
        $start = 0;
        if($page > 1)
        {
           $start = ($page - 1)*15;
        }
        $list = OrderModel::where($where)->order('create_time desc')->limit($start,65)->order('create_time desc')->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                $image_list = explode(',',$v['good_images']);
                $list[$k]['good_images'] = cdnurl($image_list[0], true);
                if($v['status'] == '0')
                {
                    $text = '待出行';
                }elseif($v['status'] == '1')
                {
                    $text = '已出行';
                }else
                {
                    $text = '已取消';
                }
                $list[$k]['status'] =$text;
            }
            
        }
        $this->success('获取成功',$list);
    }
    
    public function getOrderInfo()
    {
        $out_trade_no = $this->request->post('out_trade_no', '');
        if($out_trade_no == '')
        {
            $this->error('请选择查看出行订单',[]);
        }
        $where['out_trade_no'] = $out_trade_no;
        $where['user_id'] = $this->auth->id;
        $info = OrderModel::where($where)->find();
        if(!$info)
        {
            $this->error('出行订单不存在',[]);
        }
        
        $image_list = explode(',',$info['good_images']);
        $info['good_images'] = cdnurl($image_list[0], true);
        if($info)
        {
            $text = '待出行';
        }elseif($info['status'] == '1')
        {
            $text = '已出行';
        }else
        {
            $text = '已取消';
        }
        $info['status'] =$text;
        //获取出行人
        $traver_where['id'] = ['in',$info['travelers_id']];
        $traver_list = TravelersModel::where($traver_where)->field('name,mobile,idnumber')->select();
        $info['traver_list'] = $traver_list;
        //获取二维码
        $this->success('获取成功',$info);
    }
}